#include <avr/io.h>
#include <avr/interrupt.h>

#include <inttypes.h>
#include <avr/delay.h>



#if defined (__AVR_ATmega8__)

	#define RF12_MOSI_BIT	3	
	#define RF12_MOSI_DDR	DDRB

	#define RF12_MISO_BIT	4
	#define RF12_MISO_DDR	DDRB

	#define RF12_CLK_BIT	5
	#define RF12_CLK_DDR	DDRB

	#define RF12_SS_BIT		2
	#define RF12_SS_PORT	PORTB
	#define RF12_SS_DDR		DDRB


#elif defined (__AVR_ATmega16__)


	#define RF12_MOSI_BIT	5	
	#define RF12_MOSI_DDR	DDRB

	#define RF12_MISO_BIT	6
	#define RF12_MISO_DDR	DDRB

	#define RF12_CLK_BIT	7
	#define RF12_CLK_DDR	DDRB

	#define RF12_SS_BIT		4
	#define RF12_SS_PORT	PORTB
	#define RF12_SS_DDR		DDRB

#endif





void Spi_Init(void)
{
	RF12_MISO_DDR &= ~(1 << RF12_MISO_BIT);	// set port B SPI data input to input

	RF12_CLK_DDR  |= (1 << RF12_CLK_BIT);	// set port B SPI clock to output
	RF12_MOSI_DDR |= (1 << RF12_MOSI_BIT);	// set port B SPI data out to output 
	RF12_SS_DDR   |= (1 << RF12_SS_BIT);	// set port B SPI chip select to output

	SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR0);
}



void Spi_SetChipSelect(unsigned char chip_enable)
{
	if(chip_enable)
		RF12_SS_PORT &= ~(1 << RF12_SS_BIT);	// set chip select to low (device is selected)
	else
		RF12_SS_PORT |= (1 << RF12_SS_BIT);	// set chip select to hi (device is deselected)	

}





unsigned short SpiDriver_Transaction(unsigned short DataToSet)
{
	unsigned short received = 0;
	Spi_SetChipSelect(1);


		SPDR = (DataToSet>>8)&0x00FF;
		while(!(SPSR & (1<<SPIF)));
		received = SPDR;
		received=received<<8;

		SPDR = (DataToSet)&0x00FF;
		while(!(SPSR & (1<<SPIF)));
		received |= (SPDR&0xFF);
	

	Spi_SetChipSelect(0);
	return (received);

}





/*
Todo: use interrupts
ISR (SPI_STC_vect)                         
{
 
  
}
*/



